package com.opentd.npc;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Vector;

import com.opentd.game.Game;
import com.opentd.graphics.Drawable;

public class Wave implements Drawable{
	
	public int amount = 1;
	public int health = 10;
	public int enemyID = 1;
	public Vector<Enemy> enemies;
	public static BufferedImage fullImage;
	public WaveTimer timer = new WaveTimer();
	
	private int currentEnemy = 0;
	private boolean firstLogic = true;
	private int counter = 0;
	private int counterEnd = (2500) - (Game.NPC_MOVE_SPEED *10);
	
	public boolean isFirst = true;
	public boolean isFinished = false;
	public boolean allAreIn = false;
	
	
	
	
	
	public Wave(int amt, int health, int enemyID){
		this.amount = amt;
		this.health = health;
		this.enemyID = enemyID;
		pupulateEnemies();
	}
	
	public void logic(){
		if(isFirst){
			timer.execute();
			isFirst = false;
		}
		
		if(!timer.isReady()){
			return;
		}
		//System.out.println("Logic - allAreIn = " + allAreIn);
		if(!allAreIn){
			if(firstLogic){
				addNextEnemy();
				firstLogic = false;
			}
			//System.out.println("Counter: " + counter);
			//System.out.println("Counter end: " + counterEnd);
			if(counter >= counterEnd){
				//System.out.println("Next Enemy In Wave");
				addNextEnemy();
				counter = 0;
			}
			
			counter++;
			
			if(currentEnemy == (amount)){
				allAreIn = true;
			}
		}
		boolean kill = true;
		for(Enemy e : enemies){
			if(e.inGame)//If any of the enemies are in game, then the wave will not be killed.
				kill = false;
			e.logic();
		}
		
		if(kill)
			isFinished = true;
	}
	
	private void pupulateEnemies(){
		enemies = new Vector<Enemy>();
		for(int i = 0; i < amount; i++){
			enemies.add(new Enemy(0, 0, enemyID, health));
		}
	}
	
	private void addNextEnemy(){
		enemies.elementAt(currentEnemy).addToGame();
		currentEnemy++;
	}

	@Override
	public void draw(Graphics g) {
		if(!timer.isReady()){
			g.setFont(new Font(Font.DIALOG, Font.BOLD, 50));
			g.drawString("Next Wave in: " + timer.getTimeLeft(), 50, 50);
		}
		fullImage = new BufferedImage(Game.selectedLevel.map.width * Game.Block.WIDTH,
				Game.selectedLevel.map.height * Game.Block.HEIGHT,
				BufferedImage.TRANSLUCENT);
		
		for(Enemy e : enemies){
			e.drawMe(fullImage.getGraphics());
		}
		
		for(Enemy e : enemies){
			e.drawHealth(fullImage.getGraphics());
		}
		
		g.drawImage(fullImage.getScaledInstance(Game.panel.getWidth(), Game.panel.getHeight() - Game.Levels.MAP_HEIGHT_IN_PIXELS, BufferedImage.SCALE_SMOOTH),
				0, 0, Game.panel.getWidth(),
				Game.panel.getHeight() - Game.Levels.MAP_HEIGHT_IN_PIXELS,
				null);
	}
	
}
